package org.pet.aop;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.pet.util.JWTUtils;
import org.pet.util.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//验证token
@Component//注入ioc
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 前置处理器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{

        String token = request.getHeader("Author");
        try{
            Map<String,Object> claims = JWTUtils.verifyToken(token);
            //将解析出来的数据存储到线程中
            ThreadLocalUtil.set(claims);
            return true;
        }catch (Exception e){
            //验证失败，返回状态码401
            response.setStatus(401);
            return false;
        }
    }

    /**
     * 后置处理器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放ThreadLocal
        ThreadLocalUtil.remove();
    }
}
